package com.device.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.device.domain.Station;
import com.device.domain.StationLocation;
import com.device.domain.entity.Cabinet;
import com.device.mapper.StationMapper;
import com.device.repository.StationLocationRepository;
import com.device.service.ICabinetService;
import com.device.service.IRegionService;
import com.device.service.IStationService;
import com.share.api.rule.api.RemoteFeeRuleService;
import com.share.api.rule.domain.FeeRule;
import com.share.common.security.utils.EntityAuditable.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {


    @Autowired
    StationMapper stationMapper;
    @Autowired
    ICabinetService cabinetService;
    @Autowired
    IRegionService regionService;

    //MongoDB
    @Autowired
    StationLocationRepository stationLocationRepository;

    //远程调用
    @Autowired
    RemoteFeeRuleService remoteFeeRuleService;


    //新增MongoDB
    private void add(Station station) {
        StationLocation stationLocation = new StationLocation();
        stationLocation.setId(station.getId().toString());
        stationLocation.setStationId(station.getCabinetId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocation.setCreateTime(new Date());
        stationLocationRepository.save(stationLocation);
    }


    /**
     * 查询站点列表
     */
    @Override
    public List<Station> selectStationList(Station station) {

        // 1. 查询所有站点（此时查询会自动进行分页）
        List<Station> list = stationMapper.selectStationList(station);

        // 2 处理柜机编号
        List<Long> cabinetIdList = list.stream().map(Station::getCabinetId).toList();
        Map<Long, String> cabinetIdToCabinetNoMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(cabinetIdList)) {
            List<Cabinet> cabinetList = cabinetService.list(new LambdaQueryWrapper<Cabinet>().in(Cabinet::getId, cabinetIdList));
            cabinetIdToCabinetNoMap = cabinetList.stream().collect(Collectors.toMap(Cabinet::getId, Cabinet::getCabinetNo));
        }

        // 3. 处理费用规则描述
        List<Long> feeRuleIdList = list.stream().map(Station::getFeeRuleId).toList();
        Map<Long, String> feeRuleIdToFeeRuleNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(feeRuleIdList)){
            for (Long feeRuleId : feeRuleIdList) {
                FeeRule feeRule = remoteFeeRuleService.getFeeRule(feeRuleId).getData();
                feeRuleIdToFeeRuleNameMap.put(feeRuleId, feeRule.getDescription());
            }
        }

        // 4. 插入到站点对象中
        for (Station item : list){
            item.setCabinetNo(cabinetIdToCabinetNoMap.get(item.getCabinetId()));
            item.setFeeRuleName(feeRuleIdToFeeRuleNameMap.get(item.getFeeRuleId()));
        }

        return list;
    }

    /**
     * 新增站点
     */
    @CacheEvict(value = "selectStationList", allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveStation(Station station) {
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
        //设置创建信息
        EntityUtils.setCreateInfo(station);
        save(station);

        //站点信息同步到MongoDB
        add(station);
        return 1;
    }


    /**
     * 修改站点
     */
    @Override
    @CacheEvict(value = "selectStationList", allEntries = true)
    public int updateStation(Station station) {
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
        //设置更新信息
        EntityUtils.setUpdateInfo(station);

        updateById(station);

        //同步站点位置信息到MongoDB
        StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
        if (stationLocation != null){
            stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
            stationLocationRepository.save(stationLocation);
        }else {
            add(station);
        }

        return 1;
    }



    /**
     * 删除MongoDB站点信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        for (Object id : list) {
            stationLocationRepository.deleteByStationId(Long.parseLong(id.toString()));
        }
        return super.removeByIds(list);
    }


    /**
     * 站点设置关联数据
     */
    @Override
    @CacheEvict(value = "selectStationList", allEntries = true)
    public int setData(Station station) {
        //设置更新信息
        EntityUtils.setUpdateInfo(station);
        this.updateById(station);

        //更正柜机使用状态
        Cabinet cabinet = cabinetService.getById(station.getCabinetId());
        cabinet.setStatus("1");
        cabinetService.updateById(cabinet);
        return 1;
    }
}
